//node.js自带
var path = require("path");

//插件框架
var express = require("express");
var shortid = require("shortid");
var bodyParser = require("body-parser");

//自定义模块
var essay = require("../models/essay");
var collection = require("../models/collection");

//获取配置文件
var cates = require("../config/cates");
var settings = require("../config/settings");

var router = express.Router();
var urlencodedParser = bodyParser.urlencoded({ extended: false });

router.get("/", function(req, res, next) {
  var userId = req.session.passport.user;
  if (!req.params.essayId) {
    essay.find({ user: userId }, null, { sort: { createTime: -1 } }, function(
      err,
      essays
    ) {
      res.render("editor", {
        layout: "other",
        essays: essays,
        config: settings,
        title: settings["siteName"]
      });
    });
  }
});

router.post("/add-essay", function(req, res) {
  var title = "无标题文章";
  var content = "";
  var userId = req.session.passport.user;
  //model（直接数据库的操作）
  essay.create(
    {
      title: title,
      content: content,
      user: userId
    },
    function(err, essayData) {
      res.render(
        "ajax/editor-essay-item",
        { essay: essayData, layout: null },
        function(err, html) {
          res.send({ code: 0, message: "添加成功", html: html });
        }
      );
    }
  );
});

router.post("/del-collection", urlencodedParser, function(req, res) {
  collection.remove({ _id: req.body.id }, function(err) {
    res.send({ code: 0, message: "删除成功" });
  });
});

router.post("/update-essay", urlencodedParser, function(req, res) {
  var essayId = req.body.essayId;
  var title = req.body.title;
  var content = req.body.content;
  var cate = parseInt(req.body.cate);
  var abstract = req.body.abstract;
  var userId = req.session.passport.user;
  //model（直接数据库的操作）
  console.log(req.body);
  essay.update(
    { _id: essayId },
    {
      title: title,
      content: content,
      abstract: abstract,
      user: userId,
      cate: cate
    },
    function(err, essayData) {
      res.send({ code: 0, message: "修改成功" });
    }
  );
});

router.post("/del-essay", urlencodedParser, function(req, res) {
  var essayId = req.body.essayId;
  //model（直接数据库的操作）
  essay.remove({ _id: essayId }, function(err, essayData) {
    res.send({ code: 0, message: "删除成功" });
  });
});

router.get("/collection/:label", function(req, res, next) {
  var label = req.params.label;
  console.log(label);
  collection.find({ labels: label }, function(err, collectionData) {
    console.log(collectionData);
    res.render("admin/collection", {
      layout: "other",
      collections: collectionData,
      config: settings,
      title: settings["siteName"]
    });
  });
});

router.get("/collection", function(req, res, next) {
  collection.find({}, function(err, collectionData) {
    console.log(collectionData);
    res.render("admin/collection", {
      layout: "other",
      collections: collectionData,
      config: settings,
      title: settings["siteName"]
    });
  });
});

router.post("/add-collection", urlencodedParser, function(req, res) {
  var essayLabels = req.body.essayLabels.split(/[,，\s]/);
  collection.create(
    {
      name: req.body.essayName,
      url: req.body.essayUrl,
      labels: essayLabels
    },
    function(err, essayData) {
      res.send({ code: 0, message: "添加成功" });
    }
  );
});

router.post("/update-collection", urlencodedParser, function(req, res) {
  var essayLabels = req.body.essayLabels.split(/[,，\s]/);
  var id = req.body.id;
  collection.update(
    { _id: id },
    {
      name: req.body.essayName,
      url: req.body.essayUrl,
      labels: essayLabels
    },
    function(err, essayData) {
      res.send({ code: 0, message: "修改成功" });
    }
  );
});

//路由的顺序是自上向下找，所以我们得先特殊后一般

//编辑器页面
router.get("/:essayId", function(req, res, next) {
  var userId = req.session.passport.user;
  essay.find({ user: userId }, null, { sort: { createTime: -1 } }, function(
    err,
    essays
  ) {
    essay.findById({ _id: req.params.essayId }, function(err, essayItem) {
      if (!essayItem) {
        return next(err);
      }
      console.log(cates);
      res.render("editor", {
        layout: "other",
        essays: essays,
        cates: cates,
        essayItem: essayItem,
        config: settings,
        title: settings["siteName"]
      });
    });
  });
});

module.exports = router;
